var IMAGES_BOX_CLASS = "images_box";
var IMAGES_CLASS = "images_box_content";
var ARROWS_BOX_CLASS = "images_box";
var RIGHT_ARROW_CLASS = "right_arrow";
var LEFT_ARROW_CLASS = "left_arrow";
var imagesCount = 0;
var currentPosition = 0;
var TIME_INTERVAL = 3000;
var FADE_TIME = 500;
var BLANK_TIME = 100;
var rightArrow;
var leftArrow;

$(document).ready(function () {
    initializeBox();
});

function initializeBox() {
    images = $("." + IMAGES_BOX_CLASS).find("." + IMAGES_CLASS);
    imagesCount = $(images).size();
    if (imagesCount > 0) {
        $(images).hide();
        $($(images)[0]).show();
    }
    if (imagesCount > 1) {        
        rightArrow = $("." + ARROWS_BOX_CLASS).find("." + RIGHT_ARROW_CLASS);
        leftArrow = $("." + ARROWS_BOX_CLASS).find("." + LEFT_ARROW_CLASS);
        if(rightArrow.length > 0 && leftArrow.length > 0)
        {
			rightArrowBindClick();
			leftArrowBindClick();
		}
		else
		{
			setInterval(function () { nextImage(); }, TIME_INTERVAL);			
		}
    }
}

function rightArrowClick() {
    disableArrows();
    nextImage();
    setTimeout(function () { rightArrowBindClick(); leftArrowBindClick(); }, FADE_TIME * 2 + BLANK_TIME);
}

function leftArrowClick() {
    disableArrows();
    previousImage();
    setTimeout(function () { rightArrowBindClick(); leftArrowBindClick(); }, FADE_TIME * 2 + BLANK_TIME);
}

function rightArrowBindClick() {
    $(rightArrow).click(function (e) {
        rightArrowClick();
    });
}

function leftArrowBindClick() {
    $(leftArrow).click(function (e) {
        leftArrowClick();
    });
}

function disableArrows() {
    $(rightArrow).off();
    $(leftArrow).off();
}

function nextImage() {
    toggleImageVisibility(currentPosition, null);
    toggleImageVisibility(nextPosition(), FADE_TIME + BLANK_TIME);
    clickOn = false;
}

function previousImage() {
    toggleImageVisibility(currentPosition, null);
    toggleImageVisibility(previousPosition(), FADE_TIME + BLANK_TIME);
}

function toggleImageVisibility(position, delayTime) {
    var image = $($("." + IMAGES_CLASS)[position]);
    if (delayTime)
        $(image).delay(delayTime);
    $(image).fadeToggle(FADE_TIME);
}

function nextPosition() {
    currentPosition = (currentPosition + 1) % imagesCount;
    return currentPosition;
}

function previousPosition() {    
    currentPosition = (currentPosition + (imagesCount - 1)) % imagesCount;
    return currentPosition;
}
